package com.bitbank.smartdevice.ui.base

import android.graphics.Color
import android.os.Bundle
import android.os.PersistableBundle
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import com.kunminx.architecture.business.bus.BaseBus
import com.kunminx.architecture.business.bus.IResponse
import com.kunminx.architecture.business.bus.Result
import com.qmuiteam.qmui.util.QMUIStatusBarHelper


/**
 *  Date：2018/11/22
 *  Author：xulee
 *  Desc：
 */
abstract class BaseActivity : AppCompatActivity(), IResponse {

    private var mInitResult = mutableListOf<Result>()
    private var isResumed = false

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(getLayoutID())
        BaseBus.registerResponseObserver(this)
        QMUIStatusBarHelper.translucent(this, Color.parseColor("#ffffff"))
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        initView()
    }

    abstract fun initView()

    @LayoutRes
    abstract fun getLayoutID(): Int

    override fun onResume() {
        super.onResume()
        loadInitData()
        isResumed = true
    }

    fun loadInitData() {
        if (mInitResult.size > 0) {
            for (result in mInitResult) {
                onResultHandler(result)
            }
            mInitResult.clear()
        }
    }

    abstract fun onResultHandler(result: Result)

    override fun onResult(testResult: Result) {
        if (!isResumed) {
            mInitResult.add(testResult)
            return
        }
        onResultHandler(testResult)
    }

    fun initToolbar(toolbar: Toolbar) {
        setSupportActionBar(toolbar)
        val actionBar = supportActionBar

        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true)
            actionBar.setDisplayShowTitleEnabled(false)
        }

        toolbar.setNavigationOnClickListener { finish() }
    }

    override fun onDestroy() {
        super.onDestroy()
        BaseBus.unregisterResponseObserver(this)
    }
}